
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="padding: 36px">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="课程信息" />
          <el-step title="其他信息" />
        </el-steps>
        <div style="padding: 36px">
          <el-form v-show="active === 0" ref="courseForm" :model="courseForm" :rules="rules" label-width="80px">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="courseForm.name" placeholder="请输入课程名称" style="width: 40%" />
            </el-form-item>
            <el-form-item label="适用地区" prop="province">
              <el-select
                v-model="courseForm.province"
                remote
                filterable
                placeholder="请选择地区"
                :remote-method="remoteMethod"
                :loading="selectload"
                style="width: 40%"
                @change="selectRegion"
              >
                <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程科目" prop="subject">
              <el-select v-model="courseForm.subject" filterable placeholder="请选择科目" style="width: 40%">
                <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程封面" prop="cover">
              <el-upload
                :headers="headers"
                class="avatar-uploader"
                :action="host + '/api/v1/public/uploadFile'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="courseForm.cover" :src="getMediaUrl(courseForm.cover)" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="详情轮播" prop="lbt_url">
              <el-row :gutter="10" style="margin-left: 0">
                <el-col v-for="(item, index) in courseForm.lbt_url" :key="index" style="margin-bottom: 10px" :span="6">
                  <Pictures :url="getMediaUrl(item)" :index="index" @deletefile="handleRemoveLbtUrl" />
                </el-col>
                <el-col :span="6" style="padding-left: 0">
                  <el-upload
                    :headers="headers"
                    class="avatar-uploader"
                    :action="host + '/api/v1/public/uploadFile'"
                    :show-file-list="false"
                    :on-success="handleAvatarLbtUrl"
                    :before-upload="beforeAvatarUpload"
                  >
                    <i class="el-icon-plus avatar-uploader-icon" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="课程大纲" prop="outline">
              <el-row :gutter="10" style="margin-left: 0">
                <el-col v-for="(item, index) in courseForm.outline" :key="index" style="margin-bottom: 10px" :span="6">
                  <Pictures
                    :url="getMediaUrl(item)"
                    :index="index"
                    @deletefile="(file) => handleRemove(file, 'outline')"
                  />
                </el-col>
                <el-col :span="6" style="padding-left: 0">
                  <el-upload
                    :headers="headers"
                    class="avatar-uploader"
                    :action="host + '/api/v1/public/uploadFile'"
                    :show-file-list="false"
                    :on-success="(res) => handleAvatarOutline(res, 'outline')"
                    :before-upload="beforeAvatarUpload"
                  >
                    <i class="el-icon-plus avatar-uploader-icon" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="课程状态" prop="status">
              <el-switch
                v-model="courseForm.status"
                :active-value="1"
                :inactive-value="-1"
                active-text="上架"
                inactive-text="下架"
              />
            </el-form-item>
            <!-- <el-form-item label="公开范围" prop="public_range">
              <el-select
                v-model="courseForm.public_range"
                filterable
                placeholder="请选择范围"
                style="width: 40%"
              >
                <el-option label="普通" value="普通" />
                <el-option label="VIP" value="VIP" />
                <el-option label="SVIP" value="SVIP" />
              </el-select>
            </el-form-item>-->
            <el-form-item label="课程价格" prop="price">
              <el-input-number v-model="courseForm.price" controls-position="right" placeholder="请输入课程价格" />
            </el-form-item>
            <el-form-item label="课程时长" prop="course_duration">
              <el-input-number v-model="courseForm.course_duration" controls-position="right" placeholder="请输入课程时长" />
            </el-form-item>
          </el-form>

          <el-form
            v-show="active === 1"
            ref="lecturerForm"
            :model="lecturerForm"
            :rules="rules"
            label-position="right"
            label-width="106px"
          >
            <el-form-item label="教师介绍" prop="lecturer_id">
              <el-select v-model="lecturerForm.lecturer_id" filterable placeholder="请选择教师" style="width: 40%">
                <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程等级" prop="class_type">
              <el-select v-model="lecturerForm.class_type" filterable placeholder="请选择课程等级" style="width: 40%">
                <el-option key="普通" label="普通" value="普通" />
                <el-option key="VIP" label="VIP" value="VIP" />
                <el-option key="SVIP" label="SVIP" value="SVIP" />
              </el-select>
            </el-form-item>
            <el-form-item label="集训天数" prop="training_days">
              <el-input-number
                v-model="lecturerForm.training_days"
                controls-position="right"
                placeholder="请输入集训天数"
                style="width: 40%"
              />
            </el-form-item>

            <el-form-item label="宿舍说明" prop="explain">
              <el-select v-model="lecturerForm.explain" filterable placeholder="请选择宿舍说明" style="width: 40%">
                <el-option key="自理" label="自理" value="自理" />
                <el-option key="包住" label="包住" value="包住" />
              </el-select>
            </el-form-item>
            <el-form-item label="关联网课" prop="binding_online_id">
              <el-select v-model="lecturerForm.binding_online_id" style="width: 40%" multiple placeholder="请选择">
                <el-option
                  v-for="item in onlineList"
                  :key="item.course_id"
                  :label="item.name"
                  :value="item.course_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择题库">
              <div
                style="width: 40%;height: 36px;border: 1px solid #e6ebf5;border-radius: 4px;padding-left: 14px;"
                @click="clickTopic('question_bank', questionBankNumber)"
              >{{ questionBankNumber.length > 0 ?
                `已选择：${questionBankNumber.length}` : null
              }}</div>
            </el-form-item>

            <el-form-item label="选择试卷">
              <div
                style="width: 40%;height: 36px;border: 1px solid #e6ebf5;border-radius: 4px;padding-left: 14px;"
                @click="clickTopic('examination', examinationNumber)"
              >{{ examinationNumber.length > 0 ?
                `已选择：${examinationNumber.length}` : null
              }}</div>
            </el-form-item>
            <el-form-item label="联系客服" prop="telephone">
              <el-input v-model="lecturerForm.telephone" style="width: 40%" placeholder="请输入号码" />
            </el-form-item>

            <el-form-item label="课程详细说明" prop="course_des_explain">
              <el-row :gutter="3" style="margin-left: 0">
                <el-col
                  v-for="(item, index) in lecturerForm.course_des_explain"
                  :key="index"
                  style="margin-bottom: 10px"
                  :span="6"
                >
                  <Pictures
                    :url="getMediaUrl(item)"
                    :index="index"
                    @deletefile="(file) => handleRemove(file, 'courseDes')"
                  />
                </el-col>
                <el-col :span="6">
                  <el-upload
                    :headers="headers"
                    class="avatar-uploader"
                    :action="host + '/api/v1/public/uploadFile'"
                    :show-file-list="false"
                    :on-success="(res) => handleAvatarOutline(res, 'courseDes')"
                    :before-upload="beforeAvatarUpload"
                  >
                    <i class="el-icon-plus avatar-uploader-icon" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>

            <!-- <el-form-item label="课程详细说明" prop="course_des_explain">
              <el-input
                v-model="lecturerForm.course_des_explain"
                type="textarea"
                placeholder="请输入内容"
                :rows="2"
                :maxlength="200"
                style="width: 40%"
              />
            </el-form-item> -->
          </el-form>

          <div style="float:right">
            <el-button v-show="active !== 0" style="margin-top: 12px;" @click="lastStep">上一步</el-button>
            <el-button type="primary" style="margin-top: 12px;" @click="submitForm">{{ active === 1 ? '确认' : '下一步' }}
            </el-button>
          </div>
        </div>
      </el-card>
      <Topic
        :visible-topic="visibleTopic"
        :topic-type="topicType"
        :id-list="idList"
        @cancelTopic="cancelTopic"
        @submitFormTopic="submitFormTopic"
      />
    </template>
  </BasicLayout>
</template>

<script>
import {
  getCity,
  addOfflineCourse,
  editOfflineCourse,
  getSubject,
  getOfflineDetails,
  getOnlineList
} from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
import { getLeacher } from '@/api/admin/sys-teacher'
import { treeselect } from '@/api/admin/sys-dept'
import Pictures from '@/components/Pictures'
import Topic from '@/components/Topic'
export default {
  name: 'NetworkCourse',
  components: {
    Pictures,
    Topic
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      host: '',
      active: 0,
      flagchange: 0,
      lecturerchange: 0,
      isChange: false,
      courseForm: {
        cover: null,
        status: -1,
        outline: [],
        lbt_url: [],
        subject: null
      },
      lecturerForm: {
        course_des_explain: []
      },
      course_gift: [
        {
          gift_type: 'question_bank',
          obj_ids: ''
        },
        {
          gift_type: 'examination',
          obj_ids: ''
        }
      ],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '课程科目不能为空', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '上传课程封面', trigger: 'blur' }],
        status: [{ required: true, message: '选择课程状态', trigger: 'blur' }],
        price: [
          { required: true, message: '课程价格不能为空', trigger: 'blur' }
        ],
        course_duration: [
          { required: true, message: '课程价格不能为空', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '课程简介不能为空', trigger: 'blur' }
        ],
        outline: [{ required: true, message: '上传课程大纲', trigger: 'blur' }],
        lbt_url: [{ required: true, message: '上传详情轮播', trigger: 'blur' }],
        lecturer_id: [{ required: true, message: '选择教师', trigger: 'blur' }],
        class_type: [
          { required: true, message: '选择课程等级', trigger: 'blur' }
        ],
        online_class_id: [
          { required: true, message: '选择网课班级', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '选择适用地区', trigger: 'blur' }
        ],
        course_des_explain: [
          { required: true, message: '请输入详细说明', trigger: 'blur' }
        ]
      },
      cityList: [],
      teacherList: [],
      courseId: null,
      subjectList: [],
      deptOptions: [],
      chooseValue: [],
      selectload: false,
      onlineList: [],
      topicType: '',
      visibleTopic: false,
      questionBankNumber: [],
      examinationNumber: [],
      idList: []
    }
  },
  watch: {
    courseForm: {
      deep: true,
      handler(val) {
        this.flagchange++
        if (this.flagchange > 2) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
        if (val.province) {
          getSubject({ province: val.province }).then(res => {
            this.subjectList = res?.data || []
          })
        }
      }
    },
    lecturerForm: {
      deep: true,
      handler(val) {
        this.lecturerchange++
        if (this.lecturerchange > 1) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
      }
    }
  },
  created() {
    this.host = process.env.VUE_APP_BASE_API
    getOnlineList().then(res => {
      this.onlineList = res?.data || []
    })
    getLeacher().then(res => {
      this.teacherList = res?.data || []
    })
    getCity().then(res => {
      this.cityList = res?.data || []
    })
    if (this.$route.params.course_id) {
      /** 获取课程详情 */
      this.courseId =
        this.$route.params && Number(this.$route.params.course_id)
      getOfflineDetails(this.courseId).then(response => {
        const { data = {}} = response
        const courseInfor = {
          ...data?.offline_step1,
          outline:
            data?.offline_step1?.outline?.length > 0
              ? data?.offline_step1?.outline.split(',')
              : [],
          lbt_url:
            data?.offline_step1?.lbt_url?.length > 0
              ? data?.offline_step1?.lbt_url.split(',')
              : []
        }
        this.courseForm = {
          ...courseInfor,
          price: courseInfor.price / 100
        }
        this.lecturerForm = {
          ...data?.offline_step2,
          course_des_explain: data?.offline_step2?.course_des_explain?.includes('://')
            ? data?.offline_step2?.course_des_explain.split(',')
            : []
        }
        this.course_gift = data?.offline_step2?.course_gift || [
          {
            gift_type: 'question_bank',
            obj_ids: ''
          },
          {
            gift_type: 'examination',
            obj_ids: ''
          }
        ]
        this.questionBankNumber =
          data?.offline_step2?.course_gift[0]?.obj_ids.length > 0
            ? data?.offline_step2?.course_gift[0]?.obj_ids
              .split(',')
              .map(Number)
            : []
        this.examinationNumber =
          data?.offline_step2?.course_gift[1]?.obj_ids.length > 0
            ? data?.offline_step2?.course_gift[1]?.obj_ids
              .split(',')
              .map(Number)
            : []
        this.chooseValue = [
          data?.offline_step2?.belonging_province,
          data?.offline_step2?.city,
          data?.offline_step2?.area,
          data?.offline_step2?.dept_id
        ]
      })
    }
    this.getTreeselect()
  },
  methods: {
    selectRegion(val) {
      this.courseForm.subject = null
      getSubject({ province: val }).then(res => {
        this.subjectList = res?.data || []
      })
    },
    traverseRender(data) {
      return data?.map(item => {
        return {
          key: item.id,
          value: item.id,
          label: item.label,
          children:
            item.children.length > 0 ? this.traverseRender(item.children) : null
        }
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = this.traverseRender(response?.data)
      })
    },

    // 上一步
    lastStep() {
      if (this.active-- < 1) return (this.active = 0)
    },
    // 下一步
    submitForm() {
      if (this.active === 0) {
        this.$refs['courseForm'].validate(courseValid => {
          if (courseValid) {
            this.active++
          } else {
            return
          }
        })
      } else if (this.active === 1) {
        this.$refs['lecturerForm'].validate(lecturerValid => {
          if (lecturerValid) {
            const payload = {
              offline_step1: {
                ...this.courseForm,
                outline: this.courseForm.outline.toString(),
                lbt_url: this.courseForm.lbt_url.toString(),
                price: this.courseForm.price * 100
              },
              offline_step2: {
                ...this.lecturerForm,
                buy_push: this.lecturerForm?.dept_id,
                binding_online_id: this.lecturerForm?.binding_online_id.join(),
                course_gift: this.course_gift,
                course_des_explain: this.lecturerForm.course_des_explain.toString()
              }
            }
            if (this.$route.params.course_id && this.isChange) {
              editOfflineCourse({
                ...payload,
                course_id: this.courseId
              }).then(res => {
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.$router.push('/admin/sys-course/offline')
                } else {
                  this.msgError(res.msg)
                }
              })
            } else if (this.$route.params.course_id) {
              this.$router.push('/admin/sys-course/offline')
            } else {
              addOfflineCourse(payload).then(res => {
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.$router.push('/admin/sys-course/offline')
                } else {
                  this.msgError(res.msg)
                }
              })
            }
          }
        })
      }
    },

    handleAvatarOutline(res, type) {
      if (type === 'outline') {
        this.courseForm.outline.push(res.data.full_path)
      } else {
        this.lecturerForm.course_des_explain.push(res.data.full_path)
      }
    },
    handleAvatarLbtUrl(res) {
      this.courseForm.lbt_url.push(res.data.full_path)
    },

    handleAvatarSuccess(res) {
      this.courseForm.cover = res.data.full_path
    },

    beforeAvatarUpload(file) {
      const isLt05M = file.size / 1024 / 1024 < 0.5
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt05M) {
        this.$message.error('上传头像图片大小不能超过 500k!')
      }
      return !isJPG && isLt05M
    },
    handleRemove(file, type) {
      if (type === 'outline') {
        this.courseForm.outline = this.courseForm.outline.filter(
          (item, index) => file !== index
        )
      } else {
        this.lecturerForm.course_des_explain = this.lecturerForm.course_des_explain.filter(
          (item, index) => file !== index
        )
      }
    },
    handleRemoveLbtUrl(file) {
      this.courseForm.lbt_url = this.courseForm.lbt_url.filter(
        (item, index) => file !== index
      )
    },
    handleChange(value) {
      this.lecturerForm = {
        ...this.lecturerForm,
        belonging_province: value[0],
        city: value[1],
        area: value[2],
        dept_id: value[3]
      }
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    },
    clickTopic(value, idList) {
      this.topicType = value
      this.visibleTopic = true
      this.idList = idList
    },
    cancelTopic() {
      this.visibleTopic = false
    },
    submitFormTopic(id) {
      console.log(id, 'id/...........................')
      if (id.length > 0 && this.courseId) {
        this.isChange = true
      }
      this.visibleTopic = false
      if (this.topicType === 'question_bank') {
        this.questionBankNumber = id
        this.course_gift[0].obj_ids = id.join()
      } else {
        this.examinationNumber = id
        this.course_gift[1].obj_ids = id.join()
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
</style>
